import { OnInit, Component, Input, ViewChild } from '@angular/core';
import { StudentCourseGradeGatherDTO } from 'src/app/project/model/icm/icm-student-academic/student-score/student-course-grade-gather.dto';
import { STColumn, STData } from '@delon/abc';
import { ObjectUtil } from 'src/app/project/utils/object-util';
import { TABLE_PARAMETER } from '../../setting/table-parameter';
import { StudentScoreGratherService } from 'src/app/project/service/icm/icm-student-academic/student-score/student-score-gather.service';
import { SettingsService } from '@delon/theme';
import { StudentService } from 'src/app/project/service/icm/icm-system-user/student/student.service';
import { StudentDTO } from 'src/app/project/model/icm/icm-system-user/student/student.dto';
import { StudentCourseGradeDTO } from 'src/app/project/model/icm/icm-student-academic/score-entry/student-course-grade.dto';
import { StudentScoreService } from 'src/app/project/service/icm/icm-student-academic/score-entry/student-score.service';
import { ScoreEntryDetailComponent } from '../score-entry/score-entry-detail.component';
import { format } from 'date-fns';
@Component({
  selector: 'app-student-score-list',
  templateUrl: './student-score-list.component.html',
  styles: [
    `
      :host ::ng-deep .ant-spin-container .ant-table .ant-table-scroll .ant-table-body {
        height: fit-content !important;
        margin-bottom: 1px !important;
      }
      :host ::ng-deep .ant-spin-container .ant-table {
        height: fit-content;
      }
      :host ::ng-deep .ant-spin-container .ant-table .ant-table-content {
        height: fit-content;
      }
    `,
  ],
})
export class StudentScoreListComponent implements OnInit {
  constructor(
    private studentScoreGratherService: StudentScoreGratherService,
    private settingService: SettingsService,
    private studentService: StudentService,
    private studentCourseGradeServie: StudentScoreService,
  ) {}

  @ViewChild('scoreEntryDetailComponent', { static: false })
  scoreEntryDetailComponent: ScoreEntryDetailComponent;

  /**
   * 查询参数
   */
  @Input()
  queryParams;

  /**
   * 当前登录学生id
   */
  studentId: string;

  /**
   * 当前登录学生
   */
  student: StudentDTO;

  /**
   * 学生成绩汇总数据，按学期分，每个学期有多个课程成绩
   */
  tableData: Array<StudentCourseGradeGatherDTO> = [];

  /**
   * 列表参数
   */
  TABLE_PARAMETER = ObjectUtil.deepClone(TABLE_PARAMETER);

  /**
   * 加载状态
   */
  loading: boolean;

  /**
   * 表格列定义——学期表
   */
  stColumn: STColumn[] = [
    // { title: '序号', index: 'number', width: '4%', className: 'text-center highlight' },
    {
      title: '院系/部',
      index: 'academyName',
      width: '20%',
      className: 'text-left text-truncate',
    },
    {
      title: '行政班级',
      index: 'className',
      width: '20%',
      className: 'text-left text-truncate',
    },
    {
      title: '学号',
      index: 'studentCode',
      width: '15%',
      className: 'text-left text-truncate',
    },
    {
      title: '姓名',
      index: 'studentName',
      width: '10%',
      className: 'text-left text-truncate',
    },
    {
      title: '平均学分绩点',
      render: 'averageCreditGradePoint',
      width: '10%',
      className: 'text-right text-truncate',
    },
    {
      title: '年度',
      index: 'year',
      width: '10%',
      className: 'text-center',
      format(item) {
        return `${item.year} - ${Number.parseInt(item.year, 10) + 1} 学年`;
      },
    },
    {
      title: '学期',
      index: 'termType',
      width: '10%',
      className: 'text-left',
      format(item) {
        return item.termType === 'LAST_TERM' ? '第一学期' : '第二学期';
      },
    },
  ];

  /**
   * 表格列定义——课程成绩表
   */
  childColumns: STColumn[] = [
    { title: '序号', render: 'number', width: '2%', className: 'text-center highlight' },
    {
      title: '课程/环节',
      index: 'courseCode',
      width: '8%',
      className: 'text-left text-truncate',
      format(item) {
        return `[${item.courseCode}]${item.courseName}`;
      },
    },
    {
      title: '学分',
      index: 'credit',
      width: '3%',
      type: 'number',
      className: 'text-right',
    },
    {
      title: '类别',
      index: 'courseType',
      width: '5%',
      className: 'text-left',
    },
    {
      title: '考核方式',
      index: 'evaluationMode',
      width: '3%',
      className: 'text-left',
    },
    {
      title: '修读性质',
      index: 'property',
      width: '3%',
      className: 'text-left',
    },
    {
      title: '成绩',
      index: 'grade',
      width: '3%',
      className: 'text-right',
    },
    {
      title: '取得学分',
      index: 'getCredit',
      width: '3%',
      type: 'number',
      className: 'text-right',
    },
    {
      title: '绩点',
      index: 'gradePoint',
      width: '3%',
      type: 'number',
      className: 'text-right',
    },
    {
      title: '学分绩点',
      index: 'creditGradePoint',
      width: '3%',
      type: 'number',
      className: 'text-right',
    },
    {
      title: '备注',
      index: 'remark',
      width: '5%',
      className: 'text-left',
    },
    { title: '操作', render: 'operations', width: '4%', className: 'text-center' },
  ];

  /**
   * 高亮父表格行
   */
  highlight = (record: STData, index: number) => 'bg-cyan-1';

  /**
   * 初始化数据，根据id查询所有支出详情
   */
  loadData() {
    this.loading = true;
    // 调用分页查询
    this.studentScoreGratherService
      .search(
        this.queryParams.code,
        this.queryParams.year !== null ? format(this.queryParams.year, 'YYYY') : '',
        this.queryParams.termType,
      )
      // tslint:disable-next-line: deprecation
      .subscribe(
        data => {
          if (data) {
            // 获得基础
            this.tableData = data;
            // 计算所查成绩的总平均学分绩点
            this.calculateAverageCreditGradePoint();
            this.TABLE_PARAMETER.page.total = this.tableData.length;
          }
        },
        null,
        () => {
          this.loading = false;
        },
      );
  }

  /**
   * 平均学分绩点
   * 平均绩点= { ∑（每一科绩点*每一科学分）}/该学期学分总和。
   * 课程的学分绩点 = 课程取得绩点 * 取得学分
   * 平均学分绩点 = 所有课程的学分绩点 / 所有课程的取得学分
   */
  calculateAverageCreditGradePoint() {
    // 累计学分绩点
    let creditGradePointTotal = 0;
    // 取得的总学分
    let getCreditTotal = 0;
    this.tableData.forEach(data => {
      data.studentCourseGrades.forEach(grade => {
        getCreditTotal += grade.getCredit;
        creditGradePointTotal += grade.creditGradePoint;
      });
    });
    this.tableData.forEach(data => {
      data.averageCreditGradePoint = creditGradePointTotal / getCreditTotal;
    });
  }

  /**
   * 表格事件
   * @param e event
   */
  change(e: any): void {
    if (e.type === 'dblClick') {
      this.loading = true;
      // tslint:disable-next-line: deprecation
      this.studentCourseGradeServie.findById(e.dblClick.item.id).subscribe(
        data => {
          this.scoreEntryDetailComponent.edit(true, data);
        },
        null,
        () => {
          this.loading = false;
        },
      );
    }
  }

  /**
   * 查看
   */
  view(row: StudentCourseGradeDTO) {
    // tslint:disable-next-line: deprecation
    this.studentCourseGradeServie.findById(row.id).subscribe(
      data => {
        this.scoreEntryDetailComponent.edit(true, data);
      },
      null,
      () => {
        this.loading = false;
      },
    );
  }

  ngOnInit() {
    // this.studentId = this.settingService.user.id;
    // this.studentService.findById(this.studentId).subscribe(data => {
    //   this.student = data;
    // });
    this.loadData();
  }
}
